import React from "react"
import GpContainer from "@/components/GpContainer"
import { Popup } from "@taroify/core"
import { Play, Cross } from "@taroify/icons"
import { Swiper, SwiperItem, Image, Text, Navigator, View } from "@tarojs/components"
import GpBlockTitle from "@/components/GpBlockTitle"
import GpPagination from "@/components/GpPagination"
import GpInstitutionItem from "@/components/GpInstitutionItem"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import GpIcon from "@/components/GpFontIcon"
import {
  getRankingPageData,
  getRankingInstitution,
  getCityPanelData,
  getCityInfo
} from "@/apis/index"
import Taro from "@tarojs/taro"
import { cloneDeep, dateFormat } from "@/utils/common"
import GpEmpty from "@/components/GpEmpty"
import { pageMapper, PagePath } from "@/constants/pageMap"
import { commonUrls, navigation } from "@/utils/router"
import { __CHOOSEDCITY, __LASTLOCATIONAUTHQUERY } from "@/constants/ls"
import ls from "@/utils/ls"
import { getPosition } from "@/platform/getPosition"
import clsx from "clsx"
import styles from "./index.module.scss"

const ports = [{ text: "机构排名" }]
const arrowSize = 20
type IState = {
  pagination: IPagination
  /** 榜单推荐 */
  projects: IApiRelative.IGetRankingPageData.IResData["projects"]
  list: IApiRelative.IGetRankingInstitution.IListItem[]
  hotCitys: IApiRelative.IGetCityPanelData.ICityItem[]
  citys: IApiRelative.IGetCityPanelData.ICity[]
  cityPannelVisible: boolean
  choosedCity: INullable<IApiRelative.IGetCityPanelData.ICityItem>
}
type IData = {
  citys: IApiRelative.IGetCityPanelData.ICityItem[]
}
class InstitutionRank extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      pagination: {
        page: 1,
        pageCount: 1
      },
      projects: [],
      list: [],
      hotCitys: [],
      citys: [],
      cityPannelVisible: false,
      choosedCity: {
        cityId: "",
        cityName: "全国"
      }
    }
    this.extData = {
      citys: []
    }
  }
  componentDidMount() {
    this.getPageData()
    this.getCitySelectData().then(() => {
      this.tryGetPosition()
    })
  }
  getCitySelectData = () => {
    return getCityPanelData().then(res => {
      if (res.data.success) {
        const retData = res.data.data
        const citys = retData.citys || []
        this.setState({
          hotCitys: retData.hotCitys || [],
          citys
        })
        this.extData.citys = citys.reduce((prev, next) => {
          if (next.childs && next.childs.length > 0) {
            prev.push(...next.childs)
          }
          return prev
        }, [] as IApiRelative.IGetCityPanelData.ICityItem[])
      }
    })
  }
  getPageData = () => {
    getRankingPageData().then(res => {
      if (res.data.success) {
        const projects = res.data.data.projects || []
        this.setState({
          projects
        })
      }
    })
  }
  fallbackLocation = () => {
    this.setState(
      {
        choosedCity: {
          cityId: "",
          cityName: "全国"
        }
      },
      () => {
        this.search(1)
      }
    )
  }
  locateTip = (title: string) => {
    Taro.hideLoading()
    Taro.showToast({
      title,
      icon: "none"
    })
  }
  currentCityInValidCitys = (currentCity: IApiRelative.IGetCityPanelData.ICityItem) => {
    const validCitys = this.extData.citys
    if (validCitys && validCitys.length > 0) {
      return validCitys.findIndex(l => l.cityId === currentCity.cityId) !== -1
    }
    return false
  }
  /** 是否需要再次定位 */
  shouldLocationAuthQuery = (): boolean => {
    const lastQueryDate = ls.get(__LASTLOCATIONAUTHQUERY, null)
    if (lastQueryDate) {
      if (dateFormat() === String(lastQueryDate)) {
        return false
      }
    }
    return true
  }
  saveLastLocateAuthQuery = () => {
    ls.set(__LASTLOCATIONAUTHQUERY, dateFormat())
  }
  tryGetPosition = async () => {
    const choosedCity = ls.get(__CHOOSEDCITY, null)
    if (!choosedCity) {
      if (!this.shouldLocationAuthQuery()) {
        this.fallbackLocation()
        return
      }
      try {
        const result: IGetPositionRet = await getPosition()
        if (result) {
          console.log("result----", result)
          const res = await getCityInfo({
            cityName: result.cityName,
            lat: result.lat,
            lng: result.lng,
            mapType: result.mapType
          })
          if (res.data.success) {
            this.locateTip("定位成功")
            if (this.currentCityInValidCitys(res.data.data)) {
              ls.set(__CHOOSEDCITY, res.data.data)
              this.setState(
                {
                  choosedCity: res.data.data
                },
                () => {
                  this.search(1)
                }
              )
            } else {
              console.info("[tryGetPosition] 当前定位城市不在可选城市中")
              this.fallbackLocation()
            }
          } else {
            this.locateTip("定位失败")
            this.fallbackLocation()
          }
        }
      } catch (error) {
        this.locateTip("定位失败")
        this.fallbackLocation()
      }
      this.saveLastLocateAuthQuery()
    } else {
      this.locateTip("定位成功")
      this.setState(
        {
          choosedCity
        },
        () => {
          this.search(1)
        }
      )
    }
  }
  search = (page = 1) => {
    Taro.showLoading()
    const { choosedCity } = this.state
    const search = {} as IApiRelative.IGetRankingInstitution.IParams["search"]
    if (choosedCity) {
      search.city = choosedCity.cityId
    }
    getRankingInstitution({
      search,
      pagination: {
        current: page,
        pageSize: 7
      }
    })
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const retList = retData.list || []
          this.setState({
            list: retList,
            pagination: {
              page: retData.pagination.current,
              pageCount: retData.pagination.pageCount
            }
          })
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  /** 轮播 */
  renderSwiper = () => {
    return (
      <View className="pt-20px bg-hex-fff">
        <Swiper
          className="h-248px"
          indicatorColor="rgba(255, 255, 255, 0.5)"
          indicatorActiveColor="#FFFFFF"
          circular
          indicatorDots
          autoplay
        >
          <SwiperItem>
            <Navigator
              url={commonUrls.examGuide}
              hoverClass="none"
              className="w-690px h-248px rounded-16px bg-hex-ff0 overflow-hidden mx-auto"
            >
              <Image
                src="https://static.91goodschool.com/UpFiles/public/yikao/image/banner_1.png"
                className="w-690px h-248px"
                mode="aspectFill"
              />
            </Navigator>
          </SwiperItem>
          <SwiperItem>
            <Navigator
              url={commonUrls.institution}
              hoverClass="none"
              className="w-690px h-248px rounded-16px bg-hex-ff0 overflow-hidden mx-auto"
              openType="switchTab"
            >
              <Image
                src="https://static.91goodschool.com/UpFiles/public/yikao/image/banner_2.png"
                className="w-690px h-248px"
                mode="aspectFill"
              />
            </Navigator>
          </SwiperItem>
          <SwiperItem>
            <Navigator
              url={commonUrls.news}
              hoverClass="none"
              className="w-690px h-248px rounded-16px bg-hex-ff0 overflow-hidden mx-auto"
            >
              <Image
                src="https://static.91goodschool.com/UpFiles/public/yikao/image/banner_3.png"
                className="w-690px h-248px"
                mode="aspectFill"
              />
            </Navigator>
          </SwiperItem>
        </Swiper>
      </View>
    )
  }
  handleJump = (pagePath: PagePath, query: INullable<Recordable> = null) => {
    navigation(pagePath, query)
  }
  /** 推荐榜单 */
  renderRecommendRank = () => {
    const { projects } = this.state
    const bgMap = [
      "/images/recomendRank/ms.png",
      "/images/recomendRank/yy.png",
      "/images/recomendRank/wd.png",
      "/images/recomendRank/wh.png"
    ]
    const colorMap = ["#1A8CFF", "#FF6464", "#FF7901", "#FBA70D"]
    return (
      <View className="px-30px pt-40px pb-34px bg-hex-fff">
        <View className="pb-34px">
          <GpBlockTitle title="榜单推荐" />
        </View>
        <View className="grid grid-cols-2 gap-x-20px gap-y-24px">
          {projects.map((l, index) => (
            <View
              key={l.value}
              className="w-335px h-156px box-border rounded-16px  px-32px flex flex-col justify-center relative"
              onClick={() => this.handleJump(pageMapper.ranking, { filter: l.value })}
            >
              <Image src={bgMap[index]} className="w-335px h-156px cover-image" />
              <View className="yahei-bold font-bold text-30px text-hex-fff relative z-1">
                {l.label}
              </View>
              <View
                className="h-40px box-border rounded-20px bg-hex-fff yahei font-normal text-28px text-center leading-40px box-border px-18px mt-20px relative z-1"
                style={{
                  width: "fit-content",
                  color: colorMap[index]
                }}
              >
                GO
                <Play color={colorMap[index]} />
              </View>
            </View>
          ))}
        </View>
      </View>
    )
  }
  handlePageChange = (page: number) => {
    const _pagination = cloneDeep(this.state.pagination)
    _pagination.page = page
    this.setState(
      {
        pagination: _pagination
      },
      () => {
        this.search(page)
      }
    )
  }
  /** 广州机构排行榜 */
  renderRankList = () => {
    const { list } = this.state
    const listLen = list.length
    const choosedCity = this.state.choosedCity
    return (
      <View className="px-30px mt-32px">
        <View className="pb-34px">
          <View className="flex flex-row justify-between items-center">
            <View className="yahei-bold font-bold text-36px text-hex-2c2c35">
              {choosedCity?.cityName}机构排行榜
            </View>
            <View className="flex items-center" onClick={this.openCityPannel}>
              <GpIcon icon="icon-dingweixianxing" color="#1A8BFF" size={34} />
              <Text className="yahei font-normal text-24px text-hex-b8b8bf">
                {choosedCity?.cityName || "定位"}
              </Text>
            </View>
          </View>
        </View>
        {/* 列表 */}
        <View className="flex flex-col">
          {list.length > 0 ? (
            list.map((l, index) => (
              <GpInstitutionItem
                key={l.id}
                pureProps={{ institution: l }}
                ranking={{
                  level: l.ranking,
                  levelText: "TOP" + l.ranking
                }}
                className={clsx({
                  "mb-24px": index !== listLen - 1
                })}
              />
            ))
          ) : (
            <GpEmpty />
          )}
        </View>
      </View>
    )
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  handleChooseCity = (item: IApiRelative.IGetCityPanelData.ICityItem) => {
    this.setState(
      {
        choosedCity: item,
        cityPannelVisible: false
      },
      () => {
        this.search(1)
      }
    )
  }
  openCityPannel = () => {
    this.setState({
      cityPannelVisible: true
    })
  }
  closeCityPannel = () => {
    this.setState({
      cityPannelVisible: false
    })
  }
  renderCityPannel = () => {
    const { hotCitys, citys, cityPannelVisible, choosedCity } = this.state
    return (
      <Popup
        className={styles["city-popup"]}
        placement="bottom"
        rounded
        open={cityPannelVisible}
        style={{ height: "90%" }}
        onClose={this.closeCityPannel}
      >
        <View className={styles["city-pannel"]} catchMove>
          <View className={styles["pannel-title"]}>
            <View className="yahei-bold font-bold text-32px text-hex-1d2737 text-center relative  box-border py-32px">
              <Cross
                color="#2c2c35"
                style={{
                  fontSize: arrowSize
                }}
                className="absolute right-30px top-28px"
                onClick={this.closeCityPannel}
              />
              选择城市
            </View>
          </View>
          <View className="px-30px mt-8px">
            <View className="text-hex-666 text-20px mb-24px">热门城市</View>
            <View className="grid grid-cols-4 gap-12px">
              {hotCitys.map((l, index) => (
                <View
                  key={index}
                  className={clsx(styles["hot-city"], {
                    [styles["selected-city"]]: l.cityId === choosedCity?.cityId
                  })}
                  onClick={() => this.handleChooseCity(l)}
                >
                  {l.cityName}
                </View>
              ))}
            </View>
          </View>
          <View className="mt-32px">
            {/* item for loop */}
            {citys.map(l => (
              <View key={l.code}>
                <View
                  className="text-hex-999 text-24px px-30px bg-hex-f5f5f5 h-60px leading-60px box-border"
                  id={l.code}
                >
                  {l.code}
                </View>
                <View className="py-16px bg-hex-fff">
                  {l.childs &&
                    l.childs.map(child => (
                      <View
                        className={styles["city-item"]}
                        key={child.cityId}
                        onClick={() => this.handleChooseCity(child)}
                      >
                        {child.cityName}
                      </View>
                    ))}
                </View>
              </View>
            ))}
          </View>
        </View>
      </Popup>
    )
  }
  render(): React.ReactNode {
    const { pagination } = this.state
    return (
      <GpContainer>
        {this.renderCityPannel()}
        <View>
          {/* 轮播 */}
          {this.renderSwiper()}
          {/* 推荐榜单 */}
          {this.renderRecommendRank()}
          {/* 广州机构排行榜 */}
          {this.renderRankList()}
          {/* 分液器 */}
          <GpPagination
            onChange={this.handlePageChange}
            pagination={pagination}
            className="mt-20px"
          />
          {/* 快捷导航 */}
          {this.renderJumpNavs()}
          {/* 当前位置 */}
          <GpCurrentPort ports={ports} />
        </View>
        {/* 底部导航 */}
        <GpTabbar />
      </GpContainer>
    )
  }
}
export default InstitutionRank
